#!/usr/bin/python
# -*- coding: latin-1 -*-
# This script converts a Google Map URL to a TomTom GO 510 itinerary
# Copyright (C) <2007>  <Callous Crab>

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Contact information:
# Callous Crab <callouscrab+tomtompy@gmail.com>

import os
import sys
import zipfile
import codecs
import getopt


def usage():
    print 'Usage: '
    print 'tomtom.py -u <URL> [-n <iterary_name>]'

def get_itn(url, itn='', itn_path=''):

    print url, itn, itn_path

    if not itn_path:
        itn_path = os.getcwd()

    itn_path = os.path.abspath(itn_path)
    
    chunks = url.split('=&saddr')[1].split('&daddr')

    saddr =  chunks[0]
    dests = chunks[1][:chunks[1].find('&')].split('+to%3A')
    other_dests = []
    for dest in dests:
        tmp = dest
        ind = dests.index(dest)
        if dest.find('+to %') > 0:
            other_dests.extend(dest.split('+to %3A'))
            dests.remove(dest)
            dests.insert(ind, tmp.split('+to %3A'))
        elif dest.find('+t o%') > 0:
            other_dests.extend(dest.split('+t o%3A'))
            dests.remove(dest)
            dests.insert(ind, tmp.split('+t o%3A'))        
        elif dest.find('+to') > 0:
            other_dests.extend(dest.split('+to:'))
            dests.remove(dest)
            dests.insert(ind, tmp.split('+to:'))
        
    flat_dests = []
    for d in dests:
        if type(d) == type(""):
            flat_dests.append(d)
        else:
            flat_dests.extend(d)

    scols = saddr.replace('=', '').split('%40')
    line = ""
    if len(scols) > 1:
        coords = scols[1].replace('+', '').replace('.', '').split(',')
        line += coords[1].replace(' ', '')[:-1] + '|' + \
                coords[0].replace(' ', '')[:-1] + '|' + \
                scols[0].replace('+', ' ').strip() + '|2|\n'
    else:
        coords = scols[0].replace('+', '').replace('.', '').split(',')
        line += coords[1][:-1] + '|' + coords[0][:-1] + '||2|\n'

    final_lines = []
    final_lines.append(line)
    for d in flat_dests:
        line = ""
        cols = d.split('%40')
        daddr = ""
        if len(cols) > 1:
            coords = cols[1].replace('+', '').replace('.', '').split(',')
            daddr = cols[0].replace('=', '').replace('+', ' ').strip()
            line += coords[1].replace(' ', '')[:-1] + '|' + \
                    coords[0].replace(' ', '')[:-1] + '|' + \
                    daddr
        else:
            coords = cols[0].replace('+', '').replace('.', '').split(',')
            line += coords[1][:-1] + '|' + coords[0][:-1] + '|'
            daddr = "End"
        if d == flat_dests[-1]:
            line += '|2|\n'
        else:
            line += '|0|\n'
        final_lines.append(line)

    if not (saddr.split('+%40')[0].isalnum()):
        saddr = "Start"
    else:
        saddr = saddr.split('+%40')[0].replace('=', '').replace('+', ' ')

    if itn is None:
        file_name =  os.path.join(itn_path, saddr + "_" + daddr)
    else:
        file_name = os.path.join(itn_path, itn)

    write_itn_file(final_lines, file_name)
    write_toc_file(file_name)
    write_zip_file(file_name)
    #cleanup(file_name)
    print 'Done'
    return

def write_itn_file(final_lines, file_name):
    f = open(file_name + '.itn', 'w')
    f.writelines(final_lines)
    f.close()
    return


def write_toc_file(file_name):
    header = u"﻿"
    header = unicode("﻿", 'utf-8')
    data = []
    data.append('<?xml version="1.0" encoding="UTF-8"?>')    
    data.append('<TomTomToc version=\'1.0\'>')
    data.append('\t<Itinerary>')
    data.append('\t\t<Id>%s</Id>' % file_name)
    data.append('\t\t<Version>0</Version>')
    data.append('\t\t<Name>%s</Name>' % file_name.replace('_', ' '))
    data.append('\t\t<Size>16484</Size>')
    data.append('\t\t<Location>file:///./%s.zip</Location>' % file_name.replace(' ', '_'))
    data.append('\t</Itinerary>')
    data.append('</TomTomToc>')

    f = codecs.open(file_name + '.toc', encoding='utf-8', mode='a')
    f.write(header)
    f.close()
    
    f = open(file_name + '.toc', 'a')
    f.write('\n'.join(data))
    f.close()
    return

def write_zip_file(file_name):
    split_path = os.path.split(file_name)
    os.chdir(split_path[0])
    f = zipfile.ZipFile(split_path[1].replace(' ', '_') + '.zip', 'w')
    #f = zipfile.ZipFile("junk", 'w')
    f.write(file_name + '.itn')
    f.close()

def cleanup(file_name):
    os.remove(file_name + '.toc')
    os.remove(file_name + '.itn')
    return

def main(argv):
    url = ''
    itn = ''
    itn_path = ''
    
    try:
        opts, args = getopt.getopt(argv, 'u:n:p:', ['url=', 'itn=', 'path='])
    except getopt.GetoptError:
        print 'Incorrect arguments, url is required'
        usage()
        sys.exit(1)
    if len(opts) < 1:
        print 'Missing URL, -u is required!'
        usage()
        sys.exit(1)

    for opt, arg in opts:
        if opt in ('-u', '--url'):
            url = arg
        elif opt in ('-n', '--itn'):
            itn = arg
        elif opt in ('-p', '--path'):
            itn_path = arg

    get_itn(url, itn, itn_path)


##    #url = 'http://maps.google.com/maps?f=d&hl=en&geocode=&saddr=Attenhovendreef+%4050.913190,+4.739540&daddr=Appelweg+%4050.946010,+4.813 570+to%3APeerse+%4050.926460,+4.834790+to%3ASpicht+%4050.894770,+4.853630+to%3AKolverendries+%4050.893130,+4.885390+to%3AVlaai straat+%4050.917610,+4.885930+to%3AHaldertstraat+%4050.942030,+4.874350+to%3ASint-Annastraat+%4050.938500,+4.899850+to%3AHouwa artstraat+%4050.964080,+4.940150+to%3AMolijkestraat+%4050.989880,+4.929510+to%3AHerseltsebaan%2FN212+%4051.040690,+4.964020+to %3ANieuwstraat+%4051.031150,+4.943910+to%3AVeerlestraat+%4051.029640,+4.920380+to%3AOude+Mechelsebaan+%4051.011890,+4.908160+t o%3ATesteltsesteenweg+%4050.998530,+4.878820+to%3AVennestraat+%4051.006680,+4.856000+to%3ABetekomsesteenweg+%4051.012040,+4.78 8110+to%3AHeistraat+%4051.007520,+4.735300+to%3ATuindijk+%4051.022830,+4.697790+to%3AValkeniersdreef+%4050.999380,+4.654270+to %3ADomstraat+%4050.992990,+4.739260+to%3ATremelosesteenweg+%4050.993390,+4.775190+to%3ASteenweg+op+Gelrode+%4050.964830,+4.736 730+to%3AWijngaard+%4050.947190,+4.706300+to%3AErembodegemstraat+%4050.920850,+4.739380&sll=50.955832,4.818878&sspn=0.196585,0 .383835&ie=UTF8&ll=50.966644,4.815788&spn=0.196539,0.182648&z=12&om=1'

##    #url = 'http://maps.google.com/maps?f=d&hl=en&geocode=&saddr=Reed+Ave+%4037.366740,+-122.003600&daddr=CA-99+S+%4036.791810,+-119.862880+to:I-15+N+%4036.050380,+-115.180620+to:I-25+N+%4035.407300,+-105.495700+to:37.949138,-91.764078&mrcr=3&mrsp=4&sz=16&mra=dme&sll=37.950408,-91.765001&sspn=0.013519,0.027037&ie=UTF8&z=16&om=1'

##    url = 'http://maps.google.com/maps?f=d&hl=en&geocode=&saddr=37.369032,-122.00356&daddr=I-80+E+%4038.332930,+-122.018880+to:US-50+%4038.807550,+-120.096200+to:I-84+E+%4043.467780,+-116.097190+to:I-25+S+%4042.842860,+-106.212630+to:I-25+S+%4039.704170,+-104.994700+to:I-135+S%2FKS-15+S%2FUS-81+S+%4037.643710,+-97.308580+to:S+Kingshighway+Blvd+%4038.620570,+-90.266060+to:E+13th+St+%4037.954190,+-91.769870&mrcr=0&mrsp=0&sz=15&mra=dme&sll=37.378445,-121.999826&sspn=0.027248,0.054073&ie=UTF8&z=15&om=1'
    
if __name__ == "__main__":
    main(sys.argv[1:])
